package com.zm.admin.quartz;


import com.zm.admin.zmeng.domain.ZmScheduleJob;
import com.zm.admin.zmeng.mapper.ZmScheduleJobMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * Quartz Started
 * <p>
 * Spring 初始化时检测任务, 加载 Job 任务到内存
 *
 * @serial 2.0.0
 * @author 就眠儀式
 */
@Component
@Slf4j
public class QuartzStarted {

    @Resource
    private Scheduler scheduler;

    @Resource
    private ZmScheduleJobMapper scheduleJobMapper;

    /**
     * 定时任务初始化
     * 该注解：会在服务器加载Servlet的时候运行，并且只会被服务器执行一次
     */
    @PostConstruct
    public void init() {
        List<ZmScheduleJob> scheduleJobList = scheduleJobMapper.selectList(null);
        for (ZmScheduleJob scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = QuartzService.getCronTrigger(scheduler, Long.parseLong(scheduleJob.getId()));
            if (cronTrigger == null) {
                QuartzService.createJob(scheduler, scheduleJob);
            } else {
                QuartzService.updateJob(scheduler, scheduleJob);
            }
        }
    }
}
